package cn.flkj.lucia1a4a1.intermediate;

import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.util.encoders.Hex;
import sun.misc.BASE64Decoder;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.security.PrivateKey;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author : 州长在手 2021/1/5 下午2:05
 */
public class Utils {


  public static final   int SUCCESS = 200;
  public  static final int ERROR = 9999;
    /**
     * 将日期转换为字符串
     *
     * @param date date日期
     *
     * @return 日期字符串
     */
    public static String parseDateFormat(Date date) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINA);
            return sdf.format(date);
        } catch (Exception ex) {
            return "";
        }
    }


     public static PrivateKey getPrivateKeyFromBytes(String data) throws IOException {
        final Reader pemReader = new StringReader(data);
        final PrivateKeyInfo pemPair;
        try (PEMParser pemParser = new PEMParser(pemReader)) {
            pemPair = (PrivateKeyInfo) pemParser.readObject();
        }
        return new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getPrivateKey(pemPair);

    }

    public static JSONObject RespError(String data, String txid){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",Utils.ERROR);
        jsonObject.put("data",data);
        jsonObject.put("txid",txid);
        return jsonObject;
    }

    public static JSONObject RespSuccess(String data, String txid){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",Utils.SUCCESS);
        jsonObject.put("data",data);
        jsonObject.put("txid",txid);
        return jsonObject;
    }

    public static byte[] base64Str2Byte(String str) throws IOException {
        return new BASE64Decoder().decodeBuffer(str);
    }

    public static byte[] hexStr2Byte(String str)  {
        return  Hex.decode(str);
    }
}
